﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
using System.Xml;
using System.Xml.Serialization;

namespace ClickNET.Serialization
{
    public class SerializationManager
    {
        public sealed class Xml
        {
            private static readonly Encoding DEFAULT_ENCODING = Encoding.UTF8;

            /// <summary>
            /// Method to convert a custom Object to XML file
            /// </summary>
            /// <param name="obj">Object that is to be serialized to XML</param>
            /// <param name="filePath">Path to save xml</param>
            public static void ObjectToXMLFile(Object obj, string filePath)
            {
                using (TextWriter writer = new StreamWriter(filePath, false, DEFAULT_ENCODING))
                {
                    XmlSerializer xs = new XmlSerializer(obj.GetType());
                    xs.Serialize(writer, obj);
                }
            }

            /// <summary>
            /// Method to convert an XML serialized object back into an object
            /// </summary>
            /// <param name="filePath">Path to serialized xml</param>
            public static object ObjectFromXMLFile(string filePath, Type type)
            {
                using (TextReader reader = new StreamReader(filePath, DEFAULT_ENCODING))
                {
                    return SerializationManager.Xml.ObjectFromXML(reader, type);
                }
            }

            /// <summary>
            /// Method to convert a serialized xml object back into an object
            /// </summary>
            /// <param name="xml">Serialized xml</param>
            /// <param name="t">Object's Type</param>
            /// <returns>DeSerialized Object</returns>
            public static object ObjectFromXML(TextReader tr, Type t)
            {
                try
                {
                    XmlSerializer serializer = new XmlSerializer(t);
                    return serializer.Deserialize(tr);
                }

                catch (Exception e)
                {
                    Log.DefaultLog.WriteLine(e);
                    throw e;
                }
            }

            /// <summary>
            /// Generic method to convert a serialized xml object back into an object
            /// </summary>
            /// <param name="xml">Serialized xml</param>
            /// <returns>DeSerialized Object</returns>
            public static T ObjectFromXML<T>(string xml)
            {
                StringReader sr = new StringReader(xml);
                return (T)ObjectFromXML(sr, typeof(T));
            }
        }
    }
}
